<template>
	<view class="password">
		<u-form :model="form" ref="uForm">
			<u-form-item label="旧密码" label-width="150rpx" prop="oldPw">
				<u-input type="password" v-model="form.oldPw" />
			</u-form-item>
			<u-form-item label="新密码" label-width="150rpx" prop="newPw">
				<u-input type="password" v-model="form.newPw" />
			</u-form-item>
			<u-form-item label="确认密码" label-width="150rpx" prop="pw">
				<u-input type="password" v-model="form.pw" />
			</u-form-item>
		</u-form>

		<u-button class="submitBtn" type="success" :ripple="true" shape="circle" @click="submit">保存</u-button>
	</view>
</template>

<script>
	import {
		editUser,
		editPassword
	} from '../../api/api'

	export default {
		data() {
			const pw = (rule, value, callback) => {
				console.log(value)
				if (value != this.form.newPw) return callback(new Error('两次输入的密码不一致'))
				else callback()
			}

			return {
				form: {
					oldPw: '',
					newPw: '',
					pw: ''
				},
				rules: {
					oldPw: [{
						required: true,
						message: '请输入旧密码',
						trigger: 'blur'
					}, {
						min: 6,
						max: 6,
						message: '请输入6位数密码',
						trigger: 'blur'
					}],
					newPw: [{
						required: true,
						message: '请输入新密码',
						trigger: 'blur'
					}, {
						min: 6,
						max: 6,
						message: '请输入6位数密码',
						trigger: 'blur'
					}],
					pw: [{
						required: true,
						message: '请再次输入密码',
						trigger: 'blur'
					}, {
						validator: pw,
						message: '两次输入的密码不一致',
						trigger: 'blur'
					}],
				}
			}
		},
		methods: {
			//提交表单
			submit() {
				this.$refs.uForm.validate(async valid => {
					if (valid) {
						const res = await editPassword(this.form)
						uni.showToast({
							title: res.msg
						})
					} else {
						console.log('验证失败')
					}
				})
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		}
	}
</script>

<style scoped lang="scss">
	.password {
		background-color: #fff;
		padding: 0 30upx;

		u-form {
			u-form-item {
				border-bottom: 1px solid #999;
			}
		}
	}
</style>
